package GUILayer;

import java.awt.BorderLayout;

import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

import ControlLayer.CustomerCtr;
import ModelLayer.Customer;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.GroupLayout.Alignment;

public class CustomerGUI extends JPanel implements ActionListener {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private CustomerCtr customerCtr;
	private DefaultTableModel customerTableModel;
	private JScrollPane customerTableScrollPane;
	private JPanel showAllCustomerPanel;
	private JTable showAllCustomerTable;
	private JPanel customerInfoPanel;
	private JPanel choicePanel;

	private JTextField textField_customerId;
	private JTextField txt_Search;
	private JTextField textField_name;
	private JTextField textField_address;
	private JTextField textField_postCode;
	private JTextField textField_city;
	private JTextField textField_phone;
	private JComboBox customerTypeList;
	private JTextField textField_discountId;

	private JButton btnSave;
	private JButton btnCreate;
	private JButton btnEdit;
	private JButton btnCancel;
	private JButton btnDelete;

	private String[] listStrings = { "PrivateCustomer", "Club", " " };

	public CustomerGUI() {
		customerCtr = new CustomerCtr();
		initialize();
	}

	public void initialize() {
		this.setLayout(new BorderLayout());

		showAllCustomerPanel = new JPanel();
		this.add(showAllCustomerPanel, BorderLayout.CENTER);
		showAllCustomerPanel.setBorder(BorderFactory
				.createTitledBorder("Customers Info"));
		showAllCustomerPanel.setLayout(new BorderLayout());

		txt_Search = new JTextField();
		txt_Search.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent arg0) {
				showAllCustomers();
			}
		});
		txt_Search.setColumns(10);

		JPanel searchPanel = new JPanel();
		showAllCustomerPanel.add(searchPanel, BorderLayout.NORTH);
		GroupLayout gl_searchPanel = new GroupLayout(searchPanel);
		gl_searchPanel.setHorizontalGroup(
			gl_searchPanel.createParallelGroup(Alignment.LEADING)
				.addComponent(txt_Search)
		);
		gl_searchPanel.setVerticalGroup(
			gl_searchPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_searchPanel.createSequentialGroup()
					.addGap(5)
					.addComponent(txt_Search, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
		);
		searchPanel.setLayout(gl_searchPanel);

		// show customer info view
		JPanel showCusotmerPanel = new JPanel();
		this.add(showCusotmerPanel, BorderLayout.EAST);
		showCusotmerPanel.setLayout(new BorderLayout());
		showCusotmerPanel.setBorder(BorderFactory
				.createTitledBorder("Customer"));

		customerInfoPanel = new JPanel();
		JLabel lblcustomerId = new JLabel("Customer Id: ");
		JLabel lblname = new JLabel("Name: ");
		JLabel lbladdress = new JLabel("Address: ");
		JLabel lblPostCode = new JLabel("PostCode: ");
		JLabel lblCity = new JLabel("City: ");
		JLabel lblPhone = new JLabel("Phone: ");
		JLabel lblCustomerType = new JLabel("Customer Type: ");
		JLabel lblDiscountId = new JLabel("Discount Id: ");
		textField_customerId = new JTextField();
		textField_customerId.setEditable(false); // Id is not able changed
		textField_name = new JTextField();
		textField_address = new JTextField();
		textField_postCode = new JTextField();
		textField_city = new JTextField();
		textField_phone = new JTextField();

		// TODO
		customerTypeList = new JComboBox(listStrings);
		customerTypeList.setSelectedIndex(2);
		customerTypeList.addActionListener(this);

		textField_discountId = new JTextField();
		GroupLayout gl = new GroupLayout(customerInfoPanel);
		customerInfoPanel.setLayout(gl);
		customerInfoPanel.setBorder(BorderFactory.createTitledBorder("Info"));
		gl.setAutoCreateGaps(true);
		gl.setAutoCreateContainerGaps(true);

		gl.setHorizontalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(lblcustomerId)
								.addComponent(lblname).addComponent(lbladdress)
								.addComponent(lblPostCode)
								.addComponent(lblCity).addComponent(lblPhone)
								.addComponent(lblCustomerType)
								.addComponent(lblDiscountId))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(textField_customerId)
								.addComponent(textField_name)
								.addComponent(textField_address)
								.addComponent(textField_postCode)
								.addComponent(textField_city)
								.addComponent(textField_phone)
								.addComponent(customerTypeList)
								.addComponent(textField_discountId)));
		gl.setVerticalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblcustomerId)
								.addComponent(textField_customerId))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblname)
								.addComponent(textField_name))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lbladdress)
								.addComponent(textField_address))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblPostCode)
								.addComponent(textField_postCode))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblCity)
								.addComponent(textField_city))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblPhone)
								.addComponent(textField_phone))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblCustomerType)
								.addComponent(customerTypeList))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(lblDiscountId)
								.addComponent(textField_discountId)));

		showCusotmerPanel.add(customerInfoPanel, BorderLayout.NORTH);

		choicePanel = new JPanel();
		choicePanel.setLayout(new FlowLayout());
		btnCreate = new JButton("Create");
		btnEdit = new JButton("Edit");
		btnDelete = new JButton("Delete");
		btnSave = new JButton("Save");
		btnCancel = new JButton("Cancel/Clear");

		choicePanel.add(btnCreate);
		choicePanel.add(btnEdit);
		choicePanel.add(btnSave);
		choicePanel.add(btnDelete);
		choicePanel.add(btnCancel);
		showCusotmerPanel.add(choicePanel, BorderLayout.CENTER);
		setBtnStartStatue();

		addCustomersTable();
		showAllCustomers();

		btnCreate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String customerType = listStrings[customerTypeList
						.getSelectedIndex()];
				try {customerCtr.insertCustomer(textField_name.getText(),
						textField_address.getText(), textField_city.getText(),
						Integer.parseInt(textField_phone.getText()),
						Integer.parseInt(textField_postCode.getText()),
						customerType,
						Integer.parseInt(textField_discountId.getText()));
				} catch (Exception ex) {
					JOptionPane.showMessageDialog(null, "Please input correct values", "Error",
							JOptionPane.ERROR_MESSAGE);
				}
				cleanTextField();
				showAllCustomers();
			}
		});
		// TODO
		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int reply = JOptionPane.showConfirmDialog(null,
						"Do you want to delete this customer ?",
						"Delete Customer", JOptionPane.YES_NO_OPTION,
						JOptionPane.WARNING_MESSAGE);
				if (reply == JOptionPane.YES_OPTION) {
					try {
						customerCtr.deleteCustomer(Integer
								.parseInt(textField_customerId.getText()));
						cleanTextField();
						setBtnStartStatue();
						showAllCustomers();
					} catch (Exception e1) {
					}
				}
			}
		});

		btnEdit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				isTextFieldEditable(true);
				btnSave.setEnabled(true);
				btnDelete.setEnabled(true);
				btnCreate.setEnabled(false);
			}
		});

		btnSave.addActionListener(new ActionListener() {
			String customerType = getCustomerType();

			public void actionPerformed(ActionEvent e) {
				try {
				customerCtr.updateCustomer(
						Integer.parseInt(textField_customerId.getText()),
						textField_name.getText(), textField_address.getText(),
						textField_city.getText(),
						Integer.parseInt(textField_phone.getText()),
						Integer.parseInt(textField_postCode.getText()),
						getCustomerType(),
						Integer.parseInt(textField_discountId.getText()));
				} catch (Exception a) {
					JOptionPane.showMessageDialog(null, "Please input correct values", "Error",
							JOptionPane.ERROR_MESSAGE);
				}
				
				setBtnStartStatue();
				showAllCustomers();
			}
		});

		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				cleanTextField();
				isTextFieldEditable(true);
				setBtnStartStatue();
			}
		});

	}

	// TODO
	public void actionPerformed(ActionEvent e) {
		JComboBox cb = (JComboBox) e.getSource();
		String list = (String) cb.getSelectedItem();
	}

	public void addCustomersTable() {
		customerTableModel = new DefaultTableModel() {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		customerTableModel.addColumn("ID");
		customerTableModel.addColumn("Customer");
		customerTableModel.addColumn("Address");
		customerTableModel.addColumn("postCode");
		customerTableModel.addColumn("City");
		customerTableModel.addColumn("Phone");
		customerTableModel.addColumn("Type");
		customerTableModel.addColumn("DiscountType");

		customerTableScrollPane = new JScrollPane();

		showAllCustomerPanel.add(customerTableScrollPane, BorderLayout.CENTER);

		showAllCustomerTable = new JTable(customerTableModel);
		showAllCustomerTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		showAllCustomerTable.setAutoCreateRowSorter(true);

		showAllCustomerTable.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				btnCreate.setEnabled(false);
				btnEdit.setEnabled(true);
				int row = showAllCustomerTable.rowAtPoint(e.getPoint());
				showCustomer(Integer.valueOf((Integer) showAllCustomerTable.getValueAt(row, 0)));
			}
		});
		customerTableScrollPane.setViewportView(showAllCustomerTable);
	}

	public void showAllCustomers() {
		
		String searchFilter = txt_Search.getText();
		
		ArrayList<Customer> customers = customerCtr.getAllCustomer();
		customerTableModel.setRowCount(0);
		for (Customer customer : customers) {
			if (((Integer) customer.getId()).toString().toLowerCase()
					.contains(searchFilter.toLowerCase())
					|| customer.getName().toLowerCase()
							.contains(searchFilter.toLowerCase()))
			try {
				customerTableModel.addRow(new Object[] { customer.getId(),
						customer.getName(), customer.getAddress(),
						customer.getPostCode(), customer.getCity(),
						customer.getPhone(),
						customer.getCustomerType().toString(),
						customer.getDiscount().getDiscountId() });
			} catch (Exception e) {
				JOptionPane.showMessageDialog(null, e, "Error",
						JOptionPane.ERROR_MESSAGE);
			}
		}

	}

	public boolean showCustomer(int customerId) {
		boolean success = true;
		Customer customer = null;
		try {
			if (customerId != 0) {
				customer = customerCtr.getCustomer(customerId);
			}
		} catch (Exception e) {
			success = false;
			JOptionPane.showMessageDialog(null, e, "Error",
					JOptionPane.ERROR_MESSAGE);
			return success;
		}

		if (success) {
			textField_customerId.setText(Integer.toString(customer.getId()));
			textField_name.setText(customer.getName());
			textField_address.setText(customer.getAddress());
			textField_postCode
					.setText(Integer.toString(customer.getPostCode()));
			textField_city.setText(customer.getCity());
			textField_phone.setText(Integer.toString(customer.getPhone()));
			selectCustomerType(customer.getCustomerType().toString());
			textField_discountId.setText(Integer.toString(customer
					.getDiscount().getDiscountId()));
			isTextFieldEditable(false);
		}
		return success;
	}

	public void refreshTable() {

	}

	public void isTextFieldEditable(boolean isEditable) {
		textField_name.setEditable(isEditable);
		textField_address.setEditable(isEditable);
		textField_postCode.setEditable(isEditable);
		textField_city.setEditable(isEditable);
		textField_phone.setEditable(isEditable);
		customerTypeList.setEditable(isEditable);
		textField_discountId.setEditable(isEditable);
	}

	public int getTextFieldId(JTextField textField) {
		int id = 0;
		try {
			id = Integer.parseInt(textField.getText());
		} catch (NumberFormatException e) {
			JOptionPane.showMessageDialog(null, "Please input number", "Error",
					JOptionPane.ERROR_MESSAGE);
		} finally {
			textField.setText("");
		}
		return id;
	}

	public void setBtnStartStatue() {
		btnCreate.setEnabled(true);
		btnEdit.setEnabled(false);
		btnDelete.setEnabled(false);
		btnSave.setEnabled(false);
	}

	public void setBtnEditStatue() {
		btnCreate.setEnabled(false);
		btnEdit.setEnabled(true);
		btnDelete.setEnabled(true);
		btnSave.setEnabled(true);
	}

	public void cleanTextField() {
		txt_Search.setText("");
		textField_customerId.setText("");
		textField_name.setText("");
		textField_address.setText("");
		textField_postCode.setText("");
		textField_city.setText("");
		textField_phone.setText("");
		customerTypeList.setSelectedIndex(2);
		textField_discountId.setText("");
	}

	public String getCustomerType() {
		String customerType = listStrings[customerTypeList.getSelectedIndex()];
		return customerType;
	}

	public void selectCustomerType(String type) {
		if (type.equals("PrivateCustomer")) {
			customerTypeList.setSelectedIndex(0);
		} else if (type.equals("Club")) {
			customerTypeList.setSelectedIndex(1);
		} else {
			customerTypeList.setSelectedIndex(2);
		}
	}

}
